//
//  SSSProcessedingViewController.m
//  SSSMerchant
//
//  Created by Darker on 2017/3/27.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSProcessedingViewController.h"
#import "SSSProcessedingAddCompleteCell.h"
#import "SSSProcessedingModel.h"

@interface SSSProcessedingViewController ()<UITableViewDelegate,UITableViewDataSource>

{
    UITableView *_listTableView;
    NSMutableArray *_dataArray;//数据源数组;
    NSInteger _currentPage;
}
///** <#注释#> */
//@property (nonatomic, strong) NSMutableArray *dataArray;

/** 请求参数 */
@property(nonatomic, strong) NSMutableDictionary *parameter;
@end

static NSString *ProcessedingID    = @"ProcessedingID";

@implementation SSSProcessedingViewController

//- (void)viewWillDisappear:(BOOL)animated{
//    
//    [super viewWillDisappear:animated];
//    
//    [_listTableView.mj_footer endRefreshing];
//    [_listTableView.mj_header endRefreshing];
//}
- (void)viewDidLoad {
    [super viewDidLoad];

    //加载视图
    [self addSubViews];
    // 加载数据
    [self loadData];
    
}
- (void)addSubViews{
    
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
    headerView.frame = CGRectMake(0, 0, KSCREEN_Width, HeigthIos6CompeteWithCurrent(57));
    [self.view addSubview:headerView];
    
    CGFloat width = KSCREEN_Width/3;
    CGFloat height = HeigthIos6CompeteWithCurrent(10);
    
    UILabel *timeLabel = [UILabel new];
    [headerView addSubview:timeLabel];
    timeLabel.backgroundColor = [UIColor clearColor];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.text = @"日期";
    timeLabel.textColor = [UIColor colorWithHex:@"666666"];
    timeLabel.font = [SSSFont systemFontOfSize:14];
    timeLabel.sd_layout
    .centerYEqualToView(headerView)
    .leftSpaceToView(headerView,0)
    .heightIs(height)
    .widthIs(width);
    
    
    //金额
    UILabel *moneyLabel = [UILabel new];
    [headerView addSubview:moneyLabel];
    moneyLabel.backgroundColor = [UIColor clearColor];
    moneyLabel.textAlignment = NSTextAlignmentCenter;
    moneyLabel.text = @"订单金额";
    moneyLabel.textColor = [UIColor colorWithHex:@"666666"];
    moneyLabel.font = [SSSFont systemFontOfSize:14];
    moneyLabel.sd_layout
    .centerYEqualToView(headerView)
    .leftSpaceToView(timeLabel,0)
    .heightIs(height)
    .widthIs(width);
    
    //让利金额
    UILabel *discountNuLabel = [UILabel new];
    [headerView addSubview:discountNuLabel];
    discountNuLabel.backgroundColor = [UIColor clearColor];
    discountNuLabel.textAlignment = NSTextAlignmentCenter;
    discountNuLabel.text = @"让利金额";
    discountNuLabel.textColor = [UIColor colorWithHex:@"666666"];
    discountNuLabel.font = [SSSFont systemFontOfSize:14];
    discountNuLabel.sd_layout
    .centerYEqualToView(headerView)
    .leftSpaceToView(moneyLabel,0)
    .heightIs(height)
    .widthIs(width);
    
    _listTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, HeigthIos6CompeteWithCurrent(57), KSCREEN_Width, KSCREEN_Height  - 64 - HeigthIos6CompeteWithCurrent(59) - HeigthIos6CompeteWithCurrent(116)-HeigthIos6CompeteWithCurrent(57)) style:UITableViewStylePlain];
    _listTableView.backgroundColor = [UIColor clearColor];
    _listTableView.delegate = self;
    _listTableView.dataSource = self;
    //_listTableView.tableHeaderView = headerView;
    _listTableView.rowHeight = HeigthIos6CompeteWithCurrent(49);
    _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_listTableView];

}
#pragma mark - 加载数据
- (void)loadData{
    
    ZDRefreshHeader *header = [ZDRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // 马上进入刷新状态
    [header beginRefreshing];
    // 设置header
    _listTableView.mj_header = header;
    
    // 上拉加载
    _listTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
-(void)loadNewData{
    
     [_listTableView.mj_footer endRefreshing];
    _currentPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(_currentPage);
    params[@"pageSize"] = @"20";
    //params[@"vid"] = @"18";
    
    self.parameter = params;
    
    [[XHRequestManager manager] getRequest:kConfigPath(kOrderProcessing) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@",responseObj);
        if ([responseObj[@"status"] intValue] == 0){
            
            if ([responseObj[@"data"][@"page"][@"pageList"] count] == 0) {
                
                showTipHudStr(@"暂无数据");
                return ;
            }
            
            NSArray *array = [SSSProcessedingModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"][@"page"][@"pageList"]];
            [_dataArray removeAllObjects];
            _dataArray = [NSMutableArray array];
            [_dataArray addObjectsFromArray:array];
            
            NSDictionary *dict = @{@"allMoney":responseObj[@"data"][@"totalMoney"],@"rangli":responseObj[@"data"][@"totalRangli"]};
            
            
            //发送通知传值
            NSNotification *notification =[NSNotification notificationWithName:@"sendProcessedingNuStr" object:nil userInfo:dict];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            //不是最后一次请求
            if (self.parameter != params) return ;
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                [_listTableView reloadData];
                
            });
            
            [_listTableView.mj_header endRefreshing];
            
            //_listTableView.mj_footer.hidden = (_currentPage == 1);
            
            if ([responseObj[@"data"][@"page"][@"hasNextPage"] intValue] == 0) {
                
                [_listTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
                
                [_listTableView.mj_header endRefreshing];
            }
            
            
        }else{
            
            showTipHudStr(kResponseMessage);
            [_listTableView.mj_header endRefreshing];
        }

        
    } failure:^(NSError * _Nonnull error) {
        
        showTipHudStr(error.localizedDescription);
        [_listTableView.mj_header endRefreshing];
        
    }];
    
//    [ZDNetManager zd_requestWithType:ZDHttpRequestTypeGet UrlString:kConfigPath(kOrderProcessing) Parameters:params SuccessBlock:^(id response) {
//        
//        XHLog(@"-----%@",response);
//        if ([response[@"status"] intValue] == 0){
//            
//            _dataArray = [SSSProcessedingModel mj_objectArrayWithKeyValuesArray:response[@"data"][@"page"][@"pageList"]];
//            
//            
//            NSDictionary *dict = @{@"allMoney":response[@"data"][@"totalMoney"],@"rangli":response[@"data"][@"totalRangli"]};
//            
//            
//            //发送通知传值
//            NSNotification *notification =[NSNotification notificationWithName:@"sendProcessedingNuStr" object:nil userInfo:dict];
//            [[NSNotificationCenter defaultCenter] postNotification:notification];
//            //不是最后一次请求
//            if (self.parameter != params) return ;
//            //回到主线程刷新表格
//            dispatch_async(dispatch_get_main_queue(), ^{
//                
//                //刷新表格
//                [_listTableView reloadData];
//                
//            });
//
//            [_listTableView.mj_header endRefreshing];
//            
//            //_listTableView.mj_footer.hidden = (_currentPage == 1);
//            
//            if ([response[@"data"][@"page"][@"hasNextPage"] intValue] == 0) {
//                
//                [_listTableView.mj_footer endRefreshingWithNoMoreData];
//                
//            }else{
//                
//                [_listTableView.mj_header endRefreshing];
//            }
//
//            
//        }else{
//            
//            showTipHudStr(responseObj[@"message"]);
//            [_listTableView.mj_header endRefreshing];
//        }
//        
//    } FailureBlock:^(NSError *error) {
//        
//        XHLog(@"---error----%@",error.localizedDescription);
//        showTipHudStr(error.localizedDescription)
//        
//    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
//        
//        
//        
//    }];
}
//上拉加载
- (void)loadMoreData{
    
    [_listTableView.mj_header endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(++_currentPage);
    params[@"pageSize"] = @"20";
    [_dataArray removeAllObjects];
    
    [[XHRequestManager manager] getRequest:kConfigPath(kOrderProcessing) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@",responseObj);
        if ([responseObj[@"status"] intValue] == 0){
            
            NSArray *array = [SSSProcessedingModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"][@"page"][@"pageList"]];
            
            [_dataArray addObjectsFromArray:array];
            
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                [_listTableView reloadData];
                
            });
            
            //_listTableView.mj_footer.hidden = (_currentPage == 1);
            
            if ([responseObj[@"data"][@"page"][@"hasNextPage"] intValue] == 0) {
                
                
                [_listTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
                
                [_listTableView.mj_footer endRefreshing];
            }
            
        }else{
            
            showTipHudStr(kResponseMessage);
            [_listTableView.mj_footer endRefreshing];
        }

        
    } failure:^(NSError * _Nonnull error) {
        
        [_listTableView.mj_footer endRefreshing];
        XHLog(@"---error----%@",error.localizedDescription);
        showTipHudStr(error.localizedDescription);
        
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Class currentClass = [SSSProcessedingAddCompleteCell  class];
    
    SSSProcessedingAddCompleteCell  *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(currentClass)];
    if (!cell) {
        cell = [[SSSProcessedingAddCompleteCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ProcessedingID];
        
    }
    cell.ProcessedingModel = _dataArray[indexPath.row];
    return cell;
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"sendProcessedingNuStr" object:nil];
}

//- (NSMutableArray *)dataArray{
//    
//    if (!_dataArray) {
//        _dataArray = [NSMutableArray array];
//    }
//    return _dataArray;
//}

@end
